//
//  TopicDetailViewController.m
//  Findif
//
//  Created by Mac on 2019/3/18.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "TopicDetailViewController.h"
#import "TopicDetailHeaderView.h"
#import "SquareHeadrerView.h"
#import "NoCommitTableViewCell.h"
//#import "SquareCommitModel.h"
#import "SquareCommitTableViewCell.h"
#import "TopicCommitModel.h"
#import "MoreCommitViewController.h"
#import "NoCommitTableViewCell.h"

@interface TopicDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray <TopicCommitModel *> * listArray;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, weak)UITextField * textField;
@property (nonatomic, weak)UIButton * sendButton;
@property (nonatomic, copy)NSString * pid;
@property (nonatomic, strong)NSDictionary * dict;

@end

@implementation TopicDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    self.title = @"话题详情";
    self.pid = @"0";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(commitSomePeoPle:) name:@"commitSomePeoPle" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PushToMoreCommit:) name:@"PushToMoreCommit" object:nil];
    [self setupUI];
}


- (void)loadData{
    
    if (self.model) {
        
        NSString * ID = [NSString stringWithFormat:@"%@",self.model.id];
        
        [[ZRNetworkTool sharedTool] getTopicCommentListWithTopic_id:ID WithBlock:^(BOOL success, id responseData) {

            if (success) {
                
                self.listArray = [NSArray yy_modelArrayWithClass:[TopicCommitModel class] json:responseData[@"data"]];
            }
            
        }];
    }else if (self.ID){
        
        [[ZRNetworkTool sharedTool] getTopicInfoWithID:self.ID WithBlock:^(BOOL success, id responseData) {

            if (success) {
                
                self.dict = responseData[@"dict"];
            }
        }];
        
        [[ZRNetworkTool sharedTool] getTopicCommentListWithTopic_id:self.ID WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            if (success) {
                
                self.listArray = [NSArray yy_modelArrayWithClass:[TopicCommitModel class] json:responseData[@"data"]];
            }
            
        }];
    }
    
}

- (void)setDict:(NSDictionary *)dict{
    
    _dict = dict;
    
    [self.tableView reloadData];
}

- (void)setListArray:(NSArray<TopicCommitModel *> *)listArray{
    
    _listArray = listArray;
    
    [self.tableView reloadData];
}

- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - kBarHeight - 65 * SCREENH6)];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
    //    tableView.rowHeight = 124 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;

    [self.tableView registerClass:[NoCommitTableViewCell class] forCellReuseIdentifier:@"TopicNoCommitCell"];
    [self.tableView registerClass:[SquareCommitTableViewCell class] forCellReuseIdentifier:@"TopicCommitCell"];
    [self.tableView registerClass:[SquareHeadrerView class] forHeaderFooterViewReuseIdentifier:@"TopicDatailHeadrerView"];
    [self.tableView registerClass:[TopicDetailHeaderView class] forHeaderFooterViewReuseIdentifier:@"TopicDetailHeaderView"];
    
    [self.view addSubview:self.tableView];
    
    UIView * bottomView = [UIView new];
    
    bottomView.backgroundColor = ZRWhiteColor;
    bottomView.userInteractionEnabled = YES;
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleRoundedRect;
    textFiled.backgroundColor = ColorWithRGB(0xE0E0E0);
    textFiled.returnKeyType = UIReturnKeyDone;
    //    textFiled.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    textFiled.tintColor = ZRBlackColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x909090);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:14 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"我来说两句~" attributes:attrs];
    textFiled.textColor = ZRBlackColor;
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14 * SCREENH6];
    textFiled.delegate = self;
    
    self.textField = textFiled;
    
    [self.bottomView addSubview:self.textField];
    
    
    UIButton * sendButton = [UIButton new];
    
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(clickSendButton) forControlEvents:UIControlEventTouchUpInside];
    sendButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    sendButton.backgroundColor = ZRBlackColor;
    sendButton.layer.cornerRadius = 5 * SCREENH6;
    sendButton.layer.masksToBounds = YES;
    
    self.sendButton = sendButton;
    
    [self.bottomView addSubview:self.sendButton];
}

- (void)viewDidLayoutSubviews{
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(-kBarHeight);
        make.height.mas_equalTo(60 * SCREENH6);
        make.leading.trailing.mas_equalTo(self.view);
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.bottomView).offset(15 * SCREENH6);
        make.centerY.mas_equalTo(self.bottomView);
        make.width.mas_equalTo(295 * SCREENH6);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
    
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.bottomView).offset(-15 * SCREENH6);
        make.leading.mas_equalTo(self.textField.mas_trailing).offset(8 * SCREENH6);
        make.centerY.mas_equalTo(self.textField);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (section == 0) {
        
        return 0;
    }else{
        
        if (self.listArray.count == 0) {
            
            return 1;
        }else{
            
            return self.listArray.count;
        }
        
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.listArray.count > 0) {
        
        SquareCommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCommitCell" forIndexPath:indexPath];
        
        cell.topicModel = self.listArray[indexPath.row];
        
        return cell;
    }else{
        
        NoCommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicNoCommitCell" forIndexPath:indexPath];
        
        return cell;
    }

}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.listArray.count > 0) {
        
        TopicCommitModel * model = self.listArray[indexPath.row];
        
        return model.rowHeight;
    }else{
        
        return 80 * SCREENH6;
    }
}



- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        TopicDetailHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"TopicDetailHeaderView"];
        
        if (self.model) {
            
            header.model = self.model;
        }else if (self.dict){
            
            header.dict = self.dict;
        }
        
        
        return header;
    }else{
        
        SquareHeadrerView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"TopicDatailHeadrerView"];
        
        header.string = @"全部讨论";
        return header;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 90 * SCREENH6;
    }else{
        
        return 50 * SCREENH6;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF4F5F6);
        }
    }else{
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF4F5F6);
        }
    }
    
}

- (void)commitSomePeoPle:(NSNotification *)noti{
    
    self.pid = noti.userInfo[@"ID"];
    NSString * user_name = noti.userInfo[@"user_name"];
    self.textField.placeholder = [NSString stringWithFormat:@"回复:%@",user_name];
    
    [self.textField becomeFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    self.textField.placeholder = @"我来说两句~";
    [self.textField resignFirstResponder];
    
    return YES;
}


- (void)clickSendButton{
    
    if (self.textField.text.length > 0) {
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        
        if (self.model) {
            
            [dict setValue:self.model.id forKey:@"topic_id"];
        }else if (self.ID){
            
            [dict setValue:self.ID forKey:@"topic_id"];
        }
        
        [dict setValue:self.textField.text forKey:@"content"];
        [dict setValue:self.pid forKey:@"pid"];
        
        [[ZRNetworkTool sharedTool] userCommentTopicWithDict:dict.copy WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            if (success) {
                
                [self.textField resignFirstResponder];
                self.textField.text = @"";
                self.textField.placeholder = @"我来说两句~";
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          [self loadData];
                                                                          
                                                                          
                                                                          self.pid = @"0";
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
        
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"评论不能为空"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    
}


- (void)PushToMoreCommit:(NSNotification *)noti{
    
    NSString * ID = noti.userInfo[@"ID"];
    
    HiddenBar;
    
    MoreCommitViewController * moreVC = [MoreCommitViewController new];
    
    moreVC.topicID = ID;
    
    [self.navigationController pushViewController:moreVC animated:YES];
}

#pragma mark - TableView 占位图
- (NSString *)xy_noDataViewMessage {
    
    return @"";
}


@end
